/**
 * 
 */
package com.ddf.interceptor;

import java.net.URLDecoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.ddf.util.Constants;


/**
 * @author DDF 2017年11月8日
 * 构想：
 * 	  关闭tomcat自己的日志记录系统，使用Log4j来记录控制台的日志记录和Hibernate的SQL记录.但缺少该部分的日志属于哪个handler，
 *   看起来全是sql和参数，不能区分每个处理的界限。因此定义一个全局的拦截器，对每个handler请求前，先记录请求路径，该方法处理开始，
 *   处理结束后再打印日志该请求结束。
 */
public class HandlerAccessInterceptor implements HandlerInterceptor {
	/** 需要保证log4j.rootLogger的输出目的地和满足对应的日志级别 */
	private Logger log = LoggerFactory.getLogger(this.getClass());
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		request.setCharacterEncoding(Constants.CHARSET_U8);
		log.info("RequestMapping [{}] progress start.......", request.getServletPath());
		if (Constants.isNotNull(request.getQueryString())) {
			log.info("QueryString: [{}]", URLDecoder.decode(request.getQueryString(), Constants.CHARSET_U8));
		}
		// 读出来之后其它方法再获取body是获取不到的，这里不再深入去做。
		/*byte []buff = new byte[1024];
		StringBuilder sbl = new StringBuilder();
		ServletInputStream inputStream = request.getInputStream();
		if (inputStream != null) {
			while (inputStream.readLine(buff, 0, buff.length) != -1) {
				sbl.append(new String(buff, Constants.CHARSET_U8));
			}
			log.info("RequestBody: [{}]", sbl.toString());
		}*/
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		log.info("RequestMapping [{}] progress end.......", request.getServletPath());
	}
}
